package service

import (
	"gitee/com.xiaoxin/go-send/model"
	"gitee/com.xiaoxin/go-send/store"
	"github.com/goccy/go-json"
	"sync"
)

type EnvService interface {
	SaveOrUpdate(envInfo model.EnvironmentInfo)
	FindById(remoteIp string) model.EnvironmentInfo
}

var (
	_       EnvService = (*envService)(nil)
	env     EnvService
	envOnce sync.Once
)

type envService struct {
	store *store.EnvStore
}

func (e *envService) FindById(remoteIp string) model.EnvironmentInfo {
	entity := e.store.FindById(remoteIp)

	var envInfo = model.EnvironmentInfo{
		Prefix:   entity.Prefix,
		RemoteIp: entity.RemoteIp,
	}
	_ = json.Unmarshal([]byte(entity.Variables), &envInfo.VariableList)
	if entity.ForceReplace == 0 {
		envInfo.ForceReplace = false
	} else {
		envInfo.ForceReplace = true
	}
	if len(envInfo.VariableList) == 0 {
		envInfo.VariableList = []model.Property{{
			Key:   "",
			Value: "",
		}}
	}
	return envInfo
}

func (e *envService) SaveOrUpdate(envInfo model.EnvironmentInfo) {
	marshal, _ := json.Marshal(envInfo.VariableList)
	entity := store.EnvironmentEntity{
		Prefix:    envInfo.Prefix,
		RemoteIp:  envInfo.RemoteIp,
		Variables: string(marshal),
	}
	if envInfo.ForceReplace {
		entity.ForceReplace = 1
	} else {
		entity.ForceReplace = 0
	}
	e.store.SaveOrUpdate(entity)
}

func NewEnvService() EnvService {
	envOnce.Do(func() {
		env = &envService{
			store: store.GetSqlite().NewEnvStore(),
		}
	})
	return env
}
